﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MathematicallySafe.HeadCounter.Data.Models;
using MathematicallySafe.HeadCounter.Services.Calculators;

namespace MathematicallySafe.HeadCounter.Services
{
    public class AttendanceCalculator: PeriodicCalculation
    {
        public AttendanceCalculator(int shortPeriod, int longPeriod) : base(shortPeriod, longPeriod) {}
        public AttendanceCalculator(int shortPeriod, int longPeriod, int endWeek) : base(shortPeriod, longPeriod, endWeek) {}

        protected override void Process(Raider raider)
        {
            raider.ShortPeriodAttendance = CalculateAttendance(raider, ShortRaidingPeriod, false);
            raider.ShortPeriodAllAttendance = CalculateAttendance(raider, ShortRaidingPeriod, true);
            
            raider.LongPeriodAttendance = CalculateAttendance(raider, LongRaidingPeriod, false);
            raider.LongPeriodAllAttendance = CalculateAttendance(raider, LongRaidingPeriod, true);

            raider.LifetimeAttendance = CalculateAttendance(raider, LifetimeRaidingPeriod, false);
            raider.LifetimeAllAttendance = CalculateAttendance(raider, LifetimeRaidingPeriod, true);
        }

        private double CalculateAttendance(Raider raider, IEnumerable<Raid> raidingPeriod, bool includingOptionalRaids) 
        {
            var raids = GetAdjustedRaidingPeriod(raider, raidingPeriod, includingOptionalRaids);

            var maxRaidCount = raids.Count();
            var attendedCount = raids.Where(r => r.RaiderIdentities.Contains(raider.Identity) || r.ExtraAttendees.Contains(raider.Identity)).Count();

            // Can be a raider but attended zero raids becuase of optional raids.
            if (attendedCount == 0) return 0.0;
            return (double) attendedCount / maxRaidCount;
        }

    }
}